﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.CMS.Sites.View;
using Kooboo.CMS.Content.Query;
using Kooboo.CMS.Content.Models;
using System.Collections.Specialized;
using Kooboo.CMS.Content.Services;
using Kooboo.CMS.Sites.Globalization;
using Kooboo.CMS.Sites;
using Kooboo.CMS.Sites.Extension.Module;

namespace Kooboo.CMS.FoodOrdering.Areas.FoodOrdering.Controllers
{
    public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public bool RequiredAdmin { get; set; }
        public void OnAuthorization(AuthorizationContext filterContext)
        {

            var loginModel = Kooboo.CMS.FoodOrdering.Areas.Customer.Models.LoginModel.Current;
            var allow = loginModel.IsAuthenticated;
            if (RequiredAdmin)
            {
                allow = loginModel.IsAdmin;
            }
            if (!allow)
            {
                UrlHelper url = new UrlHelper(filterContext.RequestContext);
                filterContext.Result = new RedirectResult(url.ModuleUrl().Action("Index"));
            }
        }
    }

    public class HomeController : Controller
    {
        //
        // GET: /FoodOrdering/Home/

        public ActionResult Index(int? dayOfWeek)
        {
            dayOfWeek = dayOfWeek ?? (int)DateTime.Now.DayOfWeek;
            ViewBag.DayOfWeek = dayOfWeek.Value;
            var restaurants = ContentHelper.TextFolder(FoodOrderingAreaRegistration.RestaurantFolderName).CreateQuery().WhereEquals("Published", true);
            return View(restaurants);
        }
        #region Order
        public ActionResult Order(string uuid, string meal)
        {
            JsonResultEntry result = new JsonResultEntry();

            if (!Customer.Models.LoginModel.Current.IsAuthenticated)
            {
                result.AddMessage("Please login first.".Label().ToString());
            }
            else
            {
                try
                {
                    Repository repository = Repository.Current;
                    var orderFolder = new TextFolder(repository, FoodOrderingAreaRegistration.OrderDetailFolderName);

                    var userName = Customer.Models.LoginModel.Current.Username;
                    string strRest = "";
                    string strFood = "";
                    string strPrice = "0";
                    string strTime = DateTime.Now.ToString("yyyyMMdd");

                    var food = new TextFolder(repository, FoodOrderingAreaRegistration.FoodFolderName)
                        .CreateQuery().WhereEquals("UUID", uuid).FirstOrDefault();

                    var rest = new TextFolder(repository, food.ParentFolder).CreateQuery().WhereEquals("UUID", food.ParentUUID).FirstOrDefault();
                    strRest = rest["Name"].ToString();
                    strFood = food["Name"].ToString();
                    strPrice = food["Price"].ToString();

                    var order = orderFolder.CreateQuery().
                        WhereEquals("User", userName).WhereEquals("OrderTime", strTime).WhereEquals("Meal", meal).FirstOrDefault();

                    NameValueCollection myCol = new NameValueCollection();
                    myCol.Add("OrderTime", strTime);
                    myCol.Add("Published", "true");
                    myCol.Add("User", userName);
                    myCol.Add("Restaurant", strRest);
                    myCol.Add("Food", strFood);
                    myCol.Add("Price", strPrice);
                    myCol.Add("Meal", meal);
                    myCol.Add("FoodUUID", uuid);
                    string orderUUID = null;

                    if (order == null) //add new order
                    {
                        orderUUID = ServiceFactory.TextContentManager.Add(repository, orderFolder, null,
                            null, myCol, null, null, "")["UUID"].ToString();

                    }
                    else // modify the order
                    {
                        orderUUID = order["UUID"].ToString();
                        ServiceFactory.TextContentManager.Update(repository, orderFolder, orderUUID, myCol, userName);
                    }
                    result.Model = new { uuid = orderUUID, rest = strRest, food = strFood, meal = meal, price = strPrice };

                }
                catch (Exception e)
                {
                    result.AddException(e);
                }

            }
            return Json(result);

        }
        #endregion
        public ActionResult Delete(string uuid)
        {
            JsonResultEntry result = new JsonResultEntry();

            var orderFolder = new TextFolder(Repository.Current, FoodOrderingAreaRegistration.OrderDetailFolderName);
            ServiceFactory.TextContentManager.Delete(Repository.Current, orderFolder, uuid);

            return Json(result);
        }
        [AuthorizeAttribute]
        public ActionResult Records(string month)
        {
            var ordered = ContentHelper.TextFolder(FoodOrderingAreaRegistration.OrderDetailFolderName)
                .CreateQuery().WhereEquals("Published", true).WhereEquals("User", Kooboo.CMS.FoodOrdering.Areas.Customer.Models.LoginModel.Current.Username);

            if (!string.IsNullOrEmpty(month))
            {
                ordered = ordered.WhereStartsWith("OrderTime", month);
            }

            ordered = ordered.OrderByDescending("OrderTime").OrderByDescending("Meal");

            return View(ordered);
        }
        [AuthorizeAttribute(RequiredAdmin = true)]
        public ActionResult Statistics()
        {
            return View();
        }
    }
}
